package com.audaque.springboot.foshanupload.core.serializer;

/**
 * @author zgb
 * @desc ...
 * @date 2022-11-24 14:30:45
 */

import com.audaque.springboot.foshanupload.core.anno.DictAnno;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 字典自定序列化类
 */
public class DictSerializer extends StdSerializer<Object> implements ContextualSerializer   {

    private static final long serialVersionUID = -6157558261755426448L;

    private String groupCode;

    public DictSerializer() {
        super(Object.class);
    }

    public DictSerializer(String groupCode) {
        super(Object.class);
        this.groupCode = groupCode;
    }

    //实例化，把字段转为json
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        DictAnno dictAnno = property.getAnnotation(DictAnno.class);
        String groupCode = dictAnno.groupCode();
        if(StringUtils.isNotBlank(groupCode)) {
            return new DictSerializer(groupCode);
        }
        return  new DictSerializer();
    }

    @SneakyThrows
    @Override
    public void serialize(Object itemCode, JsonGenerator gen, SerializerProvider provider) {
        System.out.println("groupCode:"+groupCode);
        System.out.println("itemCode:"+itemCode);

        /*
        获取键值对，这里我处理成map的方式返回给前端
        这部分要自己处理，我这里是通过一个业务类从redis中获取字典
         */
        Map<String, Object> map = new HashMap<>();
        map.put("groupCode",groupCode);
        map.put("groupName","groupName");
        map.put("itemCode",itemCode);
        map.put("itemName","itemName");
        gen.writeObject(map);
    }
}
